package com.szewec.ps.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

import com.szewec.ps.R;

/**
 * create by zzy
 */
public class GPSUtils {

    private static String TAG = GPSUtils.class.getSimpleName();
    private static GPSUtils mInstance;
    private Context mContext;
    private Criteria criteria;
    private LocationManager locationManager;
    private String provider;
    private Location location = null;

    private static LocationListener mLocationListener = new LocationListener() {

        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.d(TAG, "onStatusChanged");
        }

        // Provider被enable时触发此函数，比如GPS被打开
        @Override
        public void onProviderEnabled(String provider) {
            Log.d(TAG, "onProviderEnabled");

        }

        // Provider被disable时触发此函数，比如GPS被关闭
        @Override
        public void onProviderDisabled(String provider) {
            Log.d(TAG, "onProviderDisabled");

        }

        //当坐标改变时触发此函数，如果Provider传进相同的坐标，它就不会被触发
        @Override
        public void onLocationChanged(Location location) {
        }
    };


    private GPSUtils(Context context) {
        this.mContext = context;
    }

    public static GPSUtils getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new GPSUtils(context.getApplicationContext());
        }
        return mInstance;
    }

    /**
     * 获取地理位置，先根据GPS获取，再根据网络获取
     *
     * @return
     */
    @SuppressLint("MissingPermission")
    public Location getLocation() {
        Location location = null;
        try {
            if (mContext == null) {
                return null;
            }
            LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
            if (locationManager == null) {
                return null;
            }
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {  //从gps获取经纬度
                location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location == null) {//当GPS信号弱没获取到位置的时候再从网络获取
                    location = getLocationByNetwork(mLocationListener);
                }
            } else {    //从网络获取经纬度
                location = getLocationByNetwork(mLocationListener);
            }

        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }
        return location;
    }

    /**
     * 判断是否开启了GPS或网络定位开关
     *
     * @return
     */
    public boolean isLocationProviderEnabled() {
        boolean result = false;
        LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager == null) {
            return result;
        }
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            result = true;
        }
        return result;
    }

    /**
     * 获取地理位置，先根据GPS获取，再根据网络获取
     *
     * @return
     */
    @SuppressLint("MissingPermission")
    private Location getLocationByNetwork(LocationListener mLocationListener) {
        Location location = null;
        LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        try {
            if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mLocationListener);
                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

        return location;
    }

    /**
     * 设置GPS criteria(标准)
     */
    public Criteria getCriteria() {
        if (criteria == null) {
            criteria = new Criteria();
        }
        //设置定位精确度 Criteria.ACCURACY_COARSE比较粗略，Criteria.ACCURACY_FINE则比较精细
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        //设置不需要获取海拔方向数据
        criteria.setAltitudeRequired(false);
        //设置是否需要方位信息
        criteria.setBearingRequired(false);
        //设置是否需要海拔信息
        criteria.setAltitudeRequired(false);
        //设置允许产生资费
        criteria.setCostAllowed(false);
        //要求低耗电
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        return criteria;
    }

    @SuppressLint("MissingPermission")
    public Location getLocation(Activity activity, LocationListener locationListener, OpenGPSCallBack callBack) {
        //获取定位服务
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        provider = locationManager.getBestProvider(GPSUtils.getInstance(mContext).getCriteria(), false);

        //判断是否开启GPS定位功能
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) || locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            //判断是否有权限
            PermissionsUtils.getInstance().checkPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, new PermissionsUtils.IPermissionsResult() {
                @SuppressLint("MissingPermission")
                @Override
                public void passPermissons() {
                    //权限通过
                    location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
                    if (location == null) {//当GPS信号弱没获取到位置的时候再从网络获取
                        location = getLocationByNetwork(locationListener);
                    }
                    locationManager.requestLocationUpdates(provider, 500, 0,
                            locationListener);
                }

                @Override
                public void forbitPermissons() {
                    //拒绝权限时
                    activity.finish();
                }
            });
        } else {
            callBack.openGPS();
        }
        return location;
    }

    public interface OpenGPSCallBack {
        void openGPS();
    }


    /**
     * 获取定位信息
     *
     * @param activity
     * @param locationListener
     * @return
     */
    @SuppressLint("MissingPermission")
    public Location getLocation(Activity activity, LocationListener locationListener) {
        //获取定位服务
        locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        provider = locationManager.getBestProvider(GPSUtils.getInstance(mContext).getCriteria(), false);

        //判断是否开启定位功能
        if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) || locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            //权限通过
            location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
            if (location == null) {//当GPS信号弱没获取到位置的时候再从网络获取
                location = getLocationByNetwork(activity, locationListener);
            }
            locationManager.requestLocationUpdates(provider, 500, 0,
                    locationListener);
        } else {
            CommonUtils.openLocationSetting(activity, mContext.getResources().getString(R.string.opengps));
        }
        return location;
    }

    /**
     * 获取地理位置，先根据GPS获取，再根据网络获取
     */
    @SuppressLint("MissingPermission")
    private Location getLocationByNetwork(Activity activity, LocationListener mLocationListener) {
        Location location = null;
        LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        try {
            if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mLocationListener);
                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            } else {
                if (CommonUtils.isNetworkAvailable(mContext)) {
                    CommonUtils.openLocationSetting(activity, mContext.getResources().getString(R.string.openHighPrecisionLocation));
                }
            }
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
        }

        return location;
    }
}